/*
 Error: JSON
  	ERR:[// errors list
  			{ // Error
  			code:"%s" // error code
  			clazz:"%s" // Exception class
  			msg:"%s" // Exception message
  			stack:"%s" // Exception stack
  			}
  		]
  example: {
  	ERR:"[{code:Error1},{code:Error2}]"
  }
 Error: String
  example: "#ERR:[{code:"Error1"},{code:"Error2"}]
 */

var Error = {
	isError : function(obj) {
		if (typeof (obj) == 'object') {
			return obj.ERR != undefined;
		} else if (typeof (obj) == 'string') {
			return obj.search(/#ERR:/) == 0;
		}
		return false;
	},
	getErrors : function(obj) {
		if (Error.isError(obj)) {
			if (typeof (obj) == 'object') {
				return obj.ERR;
			} else if (typeof (obj) == 'string') {
				return eval(obj.substr(5));
			} else {
				return [];
			}
		} else {
			return [];
		}
	},
	isCode : function(obj, code) {
		var errors = Error.getErrors(obj);
		if (errors == undefined) {
			return false;
		}
		for ( var i in errors) {
			if (errors[i].code == code) {
				return true;
			}
		}
		return false;
	},
	getErrorMessages : function(obj) {
		var errors = Error.getErrors(obj);
		if (errors != undefined) {
			var errorsMsg = [];
			for ( var i in errors) {
				var error = errors[i];
				var tmp;
				if (error.code == undefined) {
					tmp = GetLocaleString("Errors.unknownerrorcode");
				} else {
					tmp = GetLocaleString("Errors." + error.code);
				}
				if (error.clazz != undefined) {
					tmp += "\nclass:'" + error.clazz + "'";
				}
				if (error.msg != undefined) {
					tmp += "\nmsg:'" + error.msg + "'";
				}
				if (error.stack != undefined) {
					tmp += "\nstack:'" + error.stack + "'";
				}
				errorsMsg.push(tmp);
			}
			return errorsMsg;
		} else {
			return [];
		}
	}
};

var isTransportError = false;

jQuery.ajaxSetup( {
	traditional : true,
	error : function(request, textStatus, errorThrown) {
		if (request.status==0){
			/*Abort*/
			return;
		}
		console.error('url:"' + this.url + '"\n,status:"' + textStatus
				+ '"\n,data:"' + this.data + '"');

		if (isTransportError == true) {
			return;
		}
		isTransportError = true;

		var win = new DialogWindowControl( {
			values : {
				Title : GetLocaleString('Errors.default.title')
			},
			buttons : [ {
				title : GetLocaleString(GetLocaleString('dialogwindow.button.ok')),
				click : function() {
					isTransportError = false;
					window.location.reload();
				}
			} ]
		}).Init().Content(GetLocaleString('Errors.ajax')).Bind('onShow',
				function() {
					return false;
				}).Center().Draggable().Show();

	}
});